<template>
  <div class="learning-data-analysis">
   <h2>用户考试记录</h2>
<div class="title-line"></div>

    <!-- 用户搜索区域 - 与LearningProgress.vue风格一致 -->
    <div class="search-section">
      <div class="user-search">
        <!-- 考试类型选择 -->
        <el-radio-group v-model="selectedExamType" class="exam-type-group" @change="handleExamTypeChange">
          <el-radio label="pastexam">考试（套卷）</el-radio>
          <el-radio label="mockexam">模拟测试（组卷）</el-radio>
        </el-radio-group>

        <el-input 
          v-model="queryUsername" 
          placeholder="请输入用户名" 
          clearable
          @keyup.enter="queryExamInfo"
          style="width: 300px">
          <template #prepend>
            <el-icon><User /></el-icon>
          </template>
        </el-input>
        <el-button 
          type="primary" 
          class="custom-primary-button"
          @click="queryExamInfo"
          :loading="isLoading">
          搜索用户
        </el-button>
        <el-button 
          class="custom-reset-button"
          @click="clearSearch">
          清除搜索
        </el-button>
      </div>

      <div v-if="selectedUser" class="user-details">
        <div class="user-name">用户名: <span class="highlight">{{ selectedUser.username }}</span></div>
      </div>
    </div>

    <!-- 学习概览卡片 - 与LearningProgress.vue风格一致 -->
    <el-card class="overview-card">
      <div class="overview-header">
        <div class="header-gradient"></div>
        <h3>考试记录概览</h3>
      </div>

      <div class="stats-container">
        <!-- 套卷统计信息 -->
        <template v-if="selectedExamType === 'pastexam' && showStats">
          <div class="stat-item">
            <div class="stat-label">套卷考试次数</div>
            <div class="stat-value">
              <span v-if="stats.examCount != null">{{ stats.examCount.toLocaleString() }}</span>
              <span v-else class="no-data">暂无数据</span>
            </div>
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
          </div>

          <div class="stat-item">
            <div class="stat-label">套卷平均分</div>
            <div class="stat-value">
              <span v-if="stats.averageScore != null">{{ stats.averageScore.toFixed(1) }}</span>
              <span v-else class="no-data">暂无数据</span>
            </div>
            <div class="stat-icon">
              <el-icon><Medal /></el-icon>
            </div>
          </div>
        </template>

        <!-- 组卷统计信息 -->
        <template v-if="selectedExamType === 'mockexam' && showStats">
          <div class="stat-item">
            <div class="stat-label">组卷考试次数</div>
            <div class="stat-value">
              <span v-if="stats.examCount != null">{{ stats.examCount.toLocaleString() }}</span>
              <span v-else class="no-data">暂无数据</span>
            </div>
            <div class="stat-icon">
              <el-icon><Folder /></el-icon>
            </div>
          </div>

          <div class="stat-item">
            <div class="stat-label">组卷平均分</div>
            <div class="stat-value">
              <span v-if="stats.averageScore != null">{{ stats.averageScore.toFixed(1) }}</span>
              <span v-else class="no-data">暂无数据</span>
            </div>
            <div class="stat-icon">
              <el-icon><Trophy /></el-icon>
            </div>
          </div>
        </template>
      </div>
    </el-card>

    <!-- 考试记录表格卡片 - 与LearningProgress.vue风格一致 -->
    <el-card class="subject-card">
      <div class="overview-header">
        <div class="header-gradient"></div>
        <h3>{{ queryUsername }} 的 {{ selectedExamType === 'pastexam' ? '套卷' : '组卷' }} 考试记录</h3>
      </div>
      
      <div v-if="showStats">
        <el-table :data="tableData" stripe style="width: 100%" class="subject-table">
          <el-table-column prop="paperType" label="试卷类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.paperType === '套卷' ? 'primary' : 'warning'">
                {{ scope.row.paperType }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="examType" label="考试类型" width="120" align="center" />
          <el-table-column 
            v-if="selectedExamType === 'pastexam'" 
            prop="examYear" 
            label="考试年份" 
            width="100" 
            align="center" 
          />
          <el-table-column label="考试日期" width="140" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.examDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalQuestions" label="总题数" width="80" align="center" />
          <el-table-column prop="correctQuestions" label="正确题数" width="100" align="center" />
          <el-table-column prop="score" label="得分" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getScoreTagType(scope.row.score)">
                {{ scope.row.score }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="用时" width="100" align="center">
            <template #default="scope">
              {{ formatTime(scope.row.totalTime) }}
            </template>
          </el-table-column>
          <el-table-column label="考试时间" width="160" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination-container">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 15, 20]"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageInfo.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <div v-else-if="showNoData" class="subject-empty">
        <p>暂无考试记录数据</p>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Document, Medal, Folder, Trophy } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  components: {
    User, Document, Medal, Folder, Trophy
  },
  setup() {
    // 用户搜索相关
    const queryUsername = ref('')
    const selectedUser = ref(null)
    const isLoading = ref(false)
    const selectedExamType = ref('pastexam') // 默认查询套卷
    const hasSearched = ref(false) // 标记是否已经执行过搜索

    // 概览数据
    const stats = ref({
      examCount: 0,
      averageScore: null
    })

    // 表格数据
    const tableData = ref([])
    const showStats = ref(false)
    const showNoData = ref(false)

    // 分页相关数据
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageInfo = ref({ total: 0 })

    // 清除搜索
    const clearSearch = () => {
      queryUsername.value = ''
      selectedUser.value = null
      stats.value = {
        examCount: 0,
        averageScore: null
      }
      tableData.value = []
      showStats.value = false
      showNoData.value = false
    }

    // 查询考试信息
    const queryExamInfo = async () => {
      if (!queryUsername.value.trim()) {
        ElMessage.warning('请输入用户名')
        return
      }

      isLoading.value = true
      hasSearched.value = true
      currentPage.value = 1 // 重置分页

      try {
        // 先搜索用户
        const searchResponse = await axios.get('/api/wrong-questions/search-user', {
          params: { username: queryUsername.value.trim() }
        })

        selectedUser.value = {
          userId: searchResponse.data.userId,
          username: searchResponse.data.username
        }

        // 获取统计数据
        const { data: statData } = await axios.get(
            `/${selectedExamType.value}/stats`,
            { params: { username: queryUsername.value } }
        )

        // 获取记录数据
        const { data: recordData } = await axios.get(
            `/${selectedExamType.value}/findByUsername`,
            {
              params: {
                username: queryUsername.value,
                pageNum: currentPage.value,
                pageSize: pageSize.value
              }
            }
        )

        // 处理统计数据
        stats.value = {
          examCount: statData.examCount || 0,
          averageScore: statData.averageScore || null
        }

        // 处理记录数据
        const processedRecords = recordData.list.map(item => ({
          ...item,
          paperType: selectedExamType.value === 'pastexam' ? '套卷' : '组卷'
        }))

        tableData.value = processedRecords
        pageInfo.value.total = recordData.total
        showStats.value = true
        showNoData.value = processedRecords.length === 0
      } catch (error) {
        console.error('查询失败:', error)
        if (error.response?.status === 404) {
          ElMessage.error('用户不存在，请检查用户名是否正确')
        } else {
          ElMessage.error('查询失败: ' + (error.response?.data?.message || error.message))
        }
        selectedUser.value = null
        stats.value = {
          examCount: 0,
          averageScore: null
        }
        tableData.value = []
        showStats.value = false
        showNoData.value = true
      } finally {
        isLoading.value = false
      }
    }

    // 处理考试类型变化
    const handleExamTypeChange = () => {
      // 只有当已经执行过搜索时才自动触发查询
      if (hasSearched.value) {
        queryExamInfo()
      }
    }

    // 分页处理
    const handlePagination = async () => {
      if (!queryUsername.value.trim()) return

      try {
        const { data: recordData } = await axios.get(
            `/${selectedExamType.value}/findByUsername`,
            {
              params: {
                username: queryUsername.value,
                pageNum: currentPage.value,
                pageSize: pageSize.value
              }
            }
        )

        const processedRecords = recordData.list.map(item => ({
          ...item,
          paperType: selectedExamType.value === 'pastexam' ? '套卷' : '组卷'
        }))

        tableData.value = processedRecords
        pageInfo.value.total = recordData.total
        showNoData.value = processedRecords.length === 0
      } catch (error) {
        console.error('获取记录失败:', error)
        tableData.value = []
        showNoData.value = true
      }
    }

    // 分页大小变化
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      handlePagination()
    }

    // 当前页变化
    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      handlePagination()
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    }

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${formatDate(dateString)} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }

    // 格式化时间（分钟转换为小时和分钟）
    const formatTime = (minutes) => {
      if (!minutes) return '0分钟'
      if (minutes < 60) return `${minutes}分钟`

      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60

      if (mins === 0) return `${hours}小时`
      return `${hours}小时${mins}分钟`
    }

    // 根据得分获取标签类型
    const getScoreTagType = (score) => {
      if (score >= 90) return 'success'
      if (score >= 70) return 'primary'
      if (score >= 60) return 'warning'
      return 'danger'
    }

    return {
      queryUsername,
      selectedUser,
      isLoading,
      selectedExamType,
      stats,
      tableData,
      showStats,
      showNoData,
      currentPage,
      pageSize,
      pageInfo,
      clearSearch,
      queryExamInfo,
      handleExamTypeChange,
      handleSizeChange,
      handleCurrentChange,
      formatDate,
      formatDateTime,
      formatTime,
      getScoreTagType
    }
  }
}
</script>

<style scoped>
/* 整体布局 */
.learning-data-analysis {
  padding: 20px;
  background-color: #f5f7fa;
}

h2 {
  margin-bottom: 0; 
  color: #1a2f54;
  padding-bottom: 0;
  font-weight: 600;
  font-size: 22px;
}
.title-line {
  width: 50px;
  height: 4px;
  background: linear-gradient(90deg, #3b527a, #4e6694);
  border-radius: 2px;
  margin-bottom: 15px;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.user-search {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 15px;
}

.exam-type-group {
  margin-right: 10px;
}

.custom-primary-button {
  /* 修改为较浅的蓝色渐变 */
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  border: none;
  color: white;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(26, 47, 84, 0.3);
}

.custom-primary-button:hover {
  /* 修改为较浅的蓝色渐变 */
  background: linear-gradient(135deg, #3b527a 0%, #4e6694 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(26, 47, 84, 0.4);
}

.custom-reset-button {
  background: #f0f2f5;
  border-color: #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}

.custom-reset-button:hover {
  background: #e4e7ed;
  color: #1a2f54;
}

.user-details {
  font-size: 15px;
  color: #606266;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

.user-details .highlight {
  font-weight: 600;
  color: #1a2f54;
}

/* 卡片通用样式 */
.overview-card, .subject-card {
  border-radius: 10px;
  margin-bottom: 24px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.overview-header {
  position: relative;
  padding: 16px 20px;
  margin-bottom: 15px;
}

.overview-header h3 {
  color: white;
  position: relative;
  z-index: 2;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  /* 修改为较浅的蓝色渐变 */
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  z-index: 1;
}

/* 统计卡片 */
.stats-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.stat-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  transition: transform 0.3s, box-shadow 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  flex: 1;
  position: relative;
  overflow: hidden;
  /* 修改为较浅的蓝色 */
  border-top: 3px solid #4e6694;
}

.stat-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.stat-label {
  font-size: 15px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #1a2f54;
  min-height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.stat-icon {
  position: absolute;
  top: 15px;
  right: 15px;
  color: #1a2f54;
  opacity: 0.1;
  font-size: 36px;
}

.no-data {
  font-size: 16px;
  color: #909399;
  font-weight: normal;
}

/* 表格卡片 */
.subject-card {
  padding-bottom: 20px;
}

.subject-table {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.subject-table .el-table__header) {
  background-color: #f0f5ff;
}

:deep(.subject-table .el-table th) {
  background-color: #f0f5ff;
  color: #1a2f54;
  font-weight: 600;
}

.subject-empty {
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f9f9f9;
  color: #909399;
  font-size: 16px;
  line-height: 1.6;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .stats-container {
    flex-wrap: wrap;
  }
  
  .stat-item {
    flex-basis: calc(50% - 10px);
  }
}

@media (max-width: 768px) {
  .user-search {
    flex-wrap: wrap;
  }
  
  .stat-item {
    flex-basis: 100%;
  }
}
</style>